package org.hk.proxy.server.utils;

import cn.hutool.core.collection.CollectionUtil;
import org.hk.proxy.server.channel.ProxyChannelManager;
import org.hk.proxy.server.db.entity.HkProxyConfig;
import org.hk.proxy.common.pojo.ClientConfig;
import org.hk.proxy.server.db.mapper.HkProxyClientMapper;
import org.hk.proxy.server.db.mapper.HkProxyConfigMapper;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class CommonUtils {
    private static HkProxyConfigMapper configMapper;
    private static HkProxyClientMapper clientMapper;
    public static void initConfig(){
        if(configMapper==null){
            configMapper = SpringUtils.getBean("hkProxyConfigMapper",HkProxyConfigMapper.class);
        }
        if(clientMapper==null){
            clientMapper = SpringUtils.getBean("hkProxyClientMapper",HkProxyClientMapper.class);
        }
        List<HkProxyConfig> proxyConfigs = configMapper.selectList(null);
        if(CollectionUtil.isNotEmpty(proxyConfigs)){
            Map<Integer, List<HkProxyConfig>> configGroup = proxyConfigs.stream().collect(Collectors.groupingBy(HkProxyConfig::getClientId));
            configGroup.forEach((k,v)->{
                ClientConfig lanInfo = new ClientConfig();
                lanInfo.setClientKey(clientMapper.selectById(k).getClientKey());
                List<ClientConfig.LanInfo> lanInfoList =v.stream().map(item->{
                    ClientConfig.LanInfo info = new ClientConfig.LanInfo();
                    info.setLanInfo(item.getProxyIp());
                    info.setServerPort(item.getOutPort());
                    return info;
                }).collect(Collectors.toList());
                lanInfo.setLanInfoList(lanInfoList);
                ProxyChannelManager.addLanInfo(lanInfo);
            });
        }
    }
}
